package com.example.chatbackend.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class AiService {
    private static final Logger logger = LoggerFactory.getLogger(AiService.class);
    private final Generation generation = new Generation();
    private final AtomicLong totalCalls = new AtomicLong(0);
    private final Map<String, AtomicLong> sessionCalls = new ConcurrentHashMap<>();
    // 存储会话历史，可以用 Map<sessionId, List<Message>> 来管理
    Map<String, List<Message>> sessionHistory = new ConcurrentHashMap<>();

    @Value("${dashscope.apiKey:}")
    private String dashscopeApiKey;

    public String generateReply(String sessionId, String userMessage) {
        String apiKey = dashscopeApiKey != null && !dashscopeApiKey.isEmpty()
                ? dashscopeApiKey
                : System.getenv("DASHSCOPE_API_KEY");

        String systemPrompt =
                "你是一个英语外教，正在和学生进行对话练习。" +
                        "请用简短、真诚的口语回复用户，每次 2~3 句话，≤60字。" +
                        "避免空话、套话，不要过度总结用户说的话。给用户抛出问题，让谈话进行下去";

        String userPrompt = "用户说：" + userMessage + "\n请你直接回应。";

        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content(systemPrompt)
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(userPrompt)
                .build();

        GenerationParam param = GenerationParam.builder()
                .apiKey(apiKey)
                .model("qwen-max")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .temperature(0.9f)
                .topP(0.8)
                .maxTokens(80)
                .build();
        try {
            long before = System.currentTimeMillis();
            totalCalls.incrementAndGet();
            sessionCalls.computeIfAbsent(sessionId == null ? "" : sessionId, k -> new AtomicLong(0)).incrementAndGet();
            GenerationResult result = generation.call(param);
            long after = System.currentTimeMillis();
            logger.info("[AI] session={} model=qwen-max latencyMs={}", sessionId, (after - before));
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            return "抱歉，我暂时无法回答。请稍后重试。";
        }
    }

    public long getTotalCalls() {
        return totalCalls.get();
    }

    public Map<String, Long> getSessionCallCounts() {
        return sessionCalls.entrySet().stream().collect(java.util.stream.Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get()))
                ;
    }
}


